package com.webserver.controller;

import com.webserver.annotation.Controller;
import com.webserver.annotation.RequestMapping;
import com.webserver.entity.User;
import com.webserver.http.HttpServeletRequest;
import com.webserver.http.HttpServeletResponse;

import java.io.*;
import java.net.URISyntaxException;
@Controller
public class UserController {
    private static File users = new File("users");
    private static File root;
    private static File staticDir;
    static {
        try {
            if (!users.exists()){
                users.mkdirs();
            }
            root = new File(UserController.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(root, "static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/regUser")
    public void reg(HttpServeletRequest request, HttpServeletResponse response){
        System.out.println("开始处理用户注册");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String agestr = request.getParameter("age");
        System.out.println(username+","+password+","+nickname+","+agestr);
        if (username==null||username.isEmpty()||password==null||password.isEmpty()||
                nickname==null||nickname.isEmpty()||agestr==null||agestr.isEmpty()
        ){
            response.sendRedirect("/reg_infor_error.html");
            return;
        }
        try {
            int age = Integer.parseInt(agestr);
            User user = new User(username,password,nickname,age);
            File file = new File(users,username+".obj");
            if (file.exists()){
                response.sendRedirect("/reg_fail.html");
                return;
            }
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
            oos.writeObject(user);
            response.sendRedirect("/reg_success.html");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @RequestMapping("/login")
    public void login(HttpServeletRequest request,HttpServeletResponse response) throws IOException, ClassNotFoundException {
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        File file = new File(users,userName+".obj");
        if (file.exists()){
            ObjectInputStream ois = new ObjectInputStream(
                    new FileInputStream(file)
            );
            User user = (User) ois.readObject();
            if (user.getPassword().equals(password)){
                response.sendRedirect("/login_success.html");
                return;
            }
        }
        response.sendRedirect("/login_fail.html");
    }
}
